package com.mega.fe.god;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.mega.fe.mixins.ClassInstanceMultiMapModifier;
import com.mega.fe.util.MEGA;
import com.mega.fe.util.NonNullIterable;
import net.minecraft.util.ClassInstanceMultiMap;

import java.util.*;
import java.util.stream.Collectors;

public class NonNullClassInstanceMultiMap<T> extends ClassInstanceMultiMap<T> {
    public static int klass_ptr;

    static {
        try {
            klass_ptr = MEGA.KLASS_PTR(NonNullClassInstanceMultiMap.class);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    public ClassInstanceMultiMapModifier<T> accessor = (ClassInstanceMultiMapModifier<T>) this;
    public NonNullClassInstanceMultiMap(Class<T> p_13531_) {
        super(p_13531_);

    }

    public boolean contains(Object p_13540_) {
        return this.find(p_13540_.getClass()).contains(p_13540_);
    }

    public <S> Collection<S> find(Class<S> p_13534_) {
        if (!accessor.baseClass().isAssignableFrom(p_13534_)) {
            throw new IllegalArgumentException("Don't know how to search for " + p_13534_);
        } else {
            List<? extends T> list = accessor.byClass().computeIfAbsent(p_13534_, (p_13538_) -> {
                List<T> l =  accessor.allInstances().stream()
                        .filter(p_13538_::isInstance)
                        .collect(Collectors.toList());
                l.removeAll(Collections.singleton(null));
                return l;
            });
            return (Collection<S>) Collections.unmodifiableCollection(list);
        }
    }

    public Iterator<T> iterator() {
        return (Iterator<T>)(accessor.allInstances().isEmpty() ? Collections.emptyIterator() : Iterators.unmodifiableIterator(new NonNullIterable<>(accessor.allInstances()).iterator()));

    }

    public List<T> getAllInstances() {
        List<T> list = accessor.allInstances();
        list.removeAll(Collections.singleton(null));
        return ImmutableList.copyOf(list);
    }

    public int size() {
        return accessor.allInstances().size();
    }
}

